﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TImSdk
{
    public class Tools
    {
        /// <summary>
        /// 获取ImSDK的配置
        /// </summary>
        /// <param name="jsonPath"></param>
        /// <returns></returns>
        public static T GetConfigSetting<T>(string jsonPath) where T : class
        {
            try
            {
                var result = GetJsonString(jsonPath);
                if (!string.IsNullOrEmpty(result))
                {
                    return JsonConvert.DeserializeObject<T>(result);
                }
                else
                {
                    Console.Write($"Tools.GetConfigSetting 地址:{jsonPath}不存在.....");
                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.Write("GetSdkConfig:" + ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 获字符串
        /// </summary>
        /// <param name="jsonPath"></param>
        /// <returns></returns>
        private static string GetJsonString(string jsonPath)
        {
            if (File.Exists(jsonPath))
            {
                using (StreamReader r = new StreamReader(jsonPath))
                {
                    return r.ReadToEnd();
                }
            }
            else
            {
                Console.Write($"Tools.GetJsonString 地址:{jsonPath}不存在.....");
                return "";
            }
        }

        public static byte[] DefaultStringToUtf8Byte(string strUnicode)
        {
            if (strUnicode == null)
            {
                return null;
            }

            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(strUnicode);
            return byteArray;
        }
       
        /// <summary>
        /// 获取UTF-8 字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetUTF8String(string str)
        {
            byte[] bytes = Encoding.Default.GetBytes(str);

            var myString = Encoding.UTF8.GetString(bytes);
            return myString;

        }

        public static string Utf8ByteToDefaultString(byte[] byteUtf8)
        {
            int length = byteUtf8.Length;
            for (int i = 0; i < byteUtf8.Length; i++)
            {
                if (byteUtf8[i] == 0)
                {
                    length = i++;
                    break;
                }
            }
            byte[] byteUnicode = System.Text.Encoding.Convert(Encoding.UTF8, Encoding.Default, byteUtf8, 0, length);
            string retstr = System.Text.Encoding.Default.GetString(byteUnicode, 0, byteUnicode.Length);
            return retstr;
        }


    }
}
